/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ortus.daemon;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author jphipps
 */
public class daemonServer extends ortus.ortusvars implements Runnable {
    private static List<cronItem> crontab = new ArrayList<cronItem>();
    private static Blocking_queue queue = null;
    private static Thread_pool pool;
    private int Port = 6666;

    public daemonServer() {

        ortus.api.Setup("ortusdaemon", "DB|Theme|FavoriteExcluder|Menu|Cron|Process");

	queue = new Blocking_queue();
	pool = new Thread_pool(10,10);
    }

    public void run() {
	    boolean serverRun = true;

	    Thread ipserver =
		new Thread()
		{	public void run()
			{	
	                  try {
			     ortus.api.DebugLog(INFO,"daemonServer: Command processor listening on port " + Port);
			     ServerSocket serverSocket = new ServerSocket(Port);
			     while(true) {
				Socket socket = serverSocket.accept();
				pool.execute(new serverWorker(socket));
			      }
			  } catch(Exception e) {
				ortus.api.DebugLog(ERROR, "daemonServer: Command processor exception: " + e);
			  }
	        }
   	    };

	    ipserver.start();

	    while(serverRun) {
		try {
			Object s;
			while( (s=queue.dequeue()) != null ) {
			   ortus.api.DebugLog(INFO,"daemonServer: starting");
			   pool.execute(new ortus.daemon.daemonProcess(s));
			}
		} catch ( Exception e) {}

		try {
			ortus.api.DebugLog(INFO,"daemonServer: sleeping");
				Thread.sleep(1000);
		} catch (InterruptedException ex) {
			ortus.api.DebugLog(ERROR,"daemonServer: sleep exception: " + ex);
		}
	    }
    }

    public static void AddQueue(Object cmd) {
	    ortus.api.DebugLog(INFO,"daemonServer: Queue: added: " + (String)((Object[])cmd)[0]);
	    queue.enqueue(cmd);
    }  
}
